package com.lovo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.bean.UserBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResponseResult;
import com.lovo.result.ResultCode;
import com.lovo.result.UserValid;
import com.lovo.service.IUserService;
import com.lovo.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@ResponseResult
@Api("用户登录控制器")
public class UserController {
    @Resource
    private IUserService service;

    @ApiOperation("登录方法")
    @PostMapping("/login")
    public Object login(String userName, String userPass) throws GlobalHandleException {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_name",userName);
        wrapper.eq("user_pass", DigestUtils.sha256Hex(userPass));
        UserBean userInfoBean = service.getOne(wrapper);
        if(userInfoBean == null){
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }
        String token = JWTUtil.createToken(userInfoBean.getUserName(),userInfoBean.getUserPass(), Calendar.MINUTE,30);
        String refreshToken = JWTUtil.createToken(userInfoBean.getUserName().toString(),userInfoBean.getUserPass(), Calendar.DATE,7);
        Map map = new HashMap();
        map.put("token",token);
        map.put("refreshToken",refreshToken);
        return map;
    }

    /**
     * 从token中获取用户对象
     * @return
     */
    @GetMapping("/token")
    @UserValid
    public Object getUserWithToken(){
        return SecurityUtils.getSubject().getPrincipal();
    }

    @GetMapping("/refreshToken")
    @UserValid
    public Object refreshToken(HttpServletRequest request){
        UserBean userInfoBean = (UserBean) request.getAttribute("user");
        return JWTUtil.createToken(userInfoBean.getUserId().toString(),userInfoBean.getUserPass(),Calendar.SECOND,10);
    }

}
